import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }

    public void createHeap(){
        for(int parent = (usedSize-1-1)/2; parent >= 0; parent--){
            siftDown(parent,this.usedSize);
        }
    }

    //向下调整创建大根堆
    private void siftDown(int parent, int usedSize) {
        int child = 2*parent+1;
        while (child < usedSize) {
            //找到左右孩子的最大值
            if(child+1 < usedSize && elem[child] < elem[child+1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                swap(elem,child,parent);
               parent = child;
               child = 2*parent+1;
            } else {
                break;
            }

        }
    }

    private void swap(int[] elem,int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child) {
        int parent = (child-1)/2;
        while (parent >= 0){
            if(elem[child] > elem[parent]){
            swap(elem,child,parent);
            child = parent;
            parent = (child-1)/2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public int poll(){
        int val = elem[0];
        swap(elem,0,usedSize-1);
        siftDown(elem[0],usedSize-1 );
        usedSize--;
        return val;
    }
    //从小到大排序建大根堆,堆排序
    //O(N)+O(N*logN) => O(N*logN)
    public void heapSort(){
        int end = usedSize-1;
        while (end > 0){
            swap(elem,0,end);
            siftDown(0,end);
            end--;
        }
    }
}
